package com.iqiao.common.util.date;

import com.iqiao.common.security.JwtUser;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * Created by flt on 2017/11/9.
 */
public class ContextUtil {

    /**
     * 取得当前登录的用户。
     * <pre>
     * 1.首先尝试从线程变量中获取获取当前用户，线程变量的是通过setCurrentUserAccount方法进行设置。
     *
     * 2.如果没有获取到则从登录用户中进行获取。
     * <pre>
     * @return
     */
    public static JwtUser getCurrentUser(){
        JwtUser jwtUser=null;
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (securityContext != null) {
            Authentication auth = securityContext.getAuthentication();
            if (auth != null) {
                Object principal = auth.getPrincipal();
                if (principal instanceof JwtUser) {
                    jwtUser=(JwtUser)principal;
                }
            }
        }

        return jwtUser;
    }

    /**
     * 取得当前用户的ID
     * @return
     */
    public static Long getCurrentUserId(){
        JwtUser jwtUser = getCurrentUser();
        if(jwtUser==null) {
            return null;
        }
        return jwtUser.getUserId();
    }
}

